<template>
  <div>
    <el-dialog title="导入员工" :visible.sync="visible" width="600px" :close-on-click-modal="false">
      <el-form ref="form" :model="dataForm" :rules="dataRule" label-width="120px">
        <el-form-item label="导入Excel文件" prop="fileData">
          <el-button type="primary" @click.stop="importExcel">导入文件</el-button>
          <a style="display: inline-block; margin-left: 20px" href="https://oss.qnhro.cn/template/worker-template.xlsx"
            download>下载模版</a>
          <el-upload v-show="false" class="upload" action="/upload" ref="upload" :on-change="onChange"
            :auto-upload="false" :show-file-list="false" :file-list="fileList" accept=".xls, .xlsx">
          </el-upload>
          <div>{{ dataForm.fileData ? dataForm.fileData.name : '' }}</div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="btn" :loading="loading" @click.stop="submit">提交</el-button>
          <el-button @click.stop="close">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'import-worker',
  data() {
    return {
      visible: false,
      loading: false,
      protocolList: [],
      projectList: [],
      fileList: [],
      dataList: [],
      dataForm: {
        fileData: null
      },
      dataRule: {
        fileData: [
          { required: true, message: '文件不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取数据列表
    init() {
      this.visible = true
    },
    importExcel() {
      this.$refs['upload'].$children[0].$refs.input.click()
    },
    onChange(file, fileList) {
      this.dataForm.fileData = file; // 保存当前选择文件
      this.readExcel(); // 调用读取数据的方法
    },
    readExcel(e) {
      let that = this;
      const files = that.dataForm.fileData;
      if (!files) {
        return false;
      }
      else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      fileReader.onload = ev => {
        const data = ev.target.result;
        const workbook = this.XLSX.read(data, {
          type: "binary"
        });
        if (workbook.SheetNames.length >= 1) {

        }
        const wsname = workbook.SheetNames[0];
        console.log("wsname", wsname)
        const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
        console.log("ws", ws)
        that.outputs = []; //清空接收数据
        this.dataList = [];
        for (var i = 0; i < ws.length; i++) {
          let name = ws[i]["姓名"]
          let sex = ws[i]["性别"]
          let idCard = ws[i]["证件号码"]
          let mobile = this.convertToString(ws[i]["手机号"])
          let bankCard = ws[i]["工资账号"]
          let factoryName = this.convertToString(ws[i]["单位名称"])
          // 转换为 JavaScript 中的日期对象
          let excelDateNumber = ws[i]["入职时间"];
          console.log("excelDateNumber", excelDateNumber)
          let joinTime = this.formatExcelDate(excelDateNumber)
          console.log("joinTime", joinTime)
          let money = ws[i]["基础工资"]
          let job = ws[i]["职位"]
          let dealerMobile = this.convertToString(ws[i]["负责人手机号"])
          let statusValue = ws[i]["是否在职"]
          let status = statusValue === "离职" ? 0 : (statusValue === "在职" ? 1 : 2);
          let leaveTimeNum = ws[i]["离职时间"]
          let leaveTime = this.formatExcelDate(leaveTimeNum)
          let settleMethod = ws[i]["结算方式"] === "日结" ? 0 : 1;
          let model = {
            "name": name,
            "mobile": mobile,
            "bankCard": bankCard,
            "sex": sex,
            "idCard": idCard,
            "factoryName": factoryName,
            "joinTime": joinTime,
            "money": money,
            "job": job,
            "dealerMobile": dealerMobile,
            "status": status,
            "leaveTime": leaveTime,
            "settleMethod": settleMethod
          }
          this.dataList.unshift(model);
        }
        this.$refs.upload.value = "";
      }
      fileReader.readAsBinaryString(files.raw);
    },
    convertToString(value) {
      if (typeof value === "string") {
        return value.trim();
      }
      if (typeof value === "number") {
        return String(value);
      }
      if (value === null || value === undefined || value === "") {
        return null;
      }
      return value.toString().trim();
    },
    formatExcelDate(numb, format = '-') {
      if (typeof numb === 'string' && numb.includes("-")) {
        return numb
      }
      const time = new Date((numb - 25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000 - 24 * 3600000 - 8 * 3600000);
      time.setYear(time.getFullYear());
      const year = time.getFullYear() + '';
      const month = (time.getMonth() + 1 + '').padStart(2, '0');
      const date = time.getDate() + '';
      if (format && format.length === 1) {
        return year + format + month + format + date;
      }
      return year + format + month + format + date;
    },
    downloadFile(url, filename) {
      function getBlob(url) {
        return new Promise(resolve => {
          const xhr = new XMLHttpRequest();

          xhr.open('GET', url, true);
          xhr.responseType = 'blob';
          xhr.onload = () => {
            if (xhr.status === 200) {
              resolve(xhr.response);
            }
          };
          xhr.send();
        });
      }
      //下载文件
      function saveAs(blob, filename) {
        const elelink = document.createElement("a");
        elelink.style.display = 'none';
        elelink.download = filename;
        console.log(url, filename)
        elelink.href = window.URL.createObjectURL(blob);
        document.body.appendChild(elelink);
        elelink.click();
        document.body.removeChild(elelink);
      }
      // 调用以上方法进行下载
      getBlob(url).then(blob => {
        saveAs(blob, filename);
      });
    },
    close() {
      this.visible = false
    },
    submit() {
      console.log("this.dataForm", this.dataForm)
      console.log("this.dataList", this.dataList)
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.fullscreenLoading = true
          this.loading = true
          this.$http({
            url: this.$http.adornUrl('/v1/worker/export'),
            method: 'POST',
            data: this.$http.adornData({ 'list': this.dataList })
          }).then(({ data }) => {
            this.fullscreenLoading = false
            this.$message({
              message: data.msg,
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.loading = false
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          }).catch(() => {
            this.loading = false
            this.fullscreenLoading = false
          })
        }
      })
    }
  }
}
</script>
